#!/bin/bash
# Ubuntu 路由器配置卸载脚本

set -e

echo "=========================================="
echo "Ubuntu 路由器配置卸载"
echo "=========================================="

# 检查 root 权限
if [ "$EUID" -ne 0 ]; then 
    echo "错误: 需要 root 权限运行此脚本"
    echo "请使用: sudo bash uninstall.sh"
    exit 1
fi

read -p "确定要卸载所有路由器配置吗? (y/N): " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo "已取消"
    exit 0
fi

echo "停止相关服务..."
systemctl stop dnsmasq 2>/dev/null || true
systemctl stop hostapd 2>/dev/null || true
systemctl stop avahi-daemon 2>/dev/null || true

echo "禁用服务..."
systemctl disable dnsmasq 2>/dev/null || true
systemctl disable hostapd 2>/dev/null || true
systemctl disable avahi-daemon 2>/dev/null || true

echo "删除 netplan 配置文件..."
rm -f /etc/netplan/01-wan-*.yaml 2>/dev/null || true
rm -f /etc/netplan/02-lan-bridge.yaml 2>/dev/null || true

echo "恢复 dnsmasq 配置..."
if [ -f /etc/dnsmasq.conf.backup ]; then
    mv /etc/dnsmasq.conf.backup /etc/dnsmasq.conf
else
    > /etc/dnsmasq.conf
fi

echo "删除 hostapd 配置..."
rm -f /etc/hostapd/hostapd.conf 2>/dev/null || true
rm -f /etc/default/hostapd 2>/dev/null || true

echo "删除 wpa_supplicant 配置..."
rm -f /etc/wpa_supplicant/wpa_supplicant.conf 2>/dev/null || true

echo "清除 iptables NAT 规则..."
iptables -t nat -F POSTROUTING 2>/dev/null || true

echo "恢复 sysctl 配置..."
rm -f /etc/sysctl.d/99-router.conf 2>/dev/null || true
sysctl -p 2>/dev/null || true

echo "删除配置目录..."
rm -rf /etc/ubuntu-router 2>/dev/null || true

echo "应用 netplan 更改..."
netplan apply 2>/dev/null || true

echo "=========================================="
echo "卸载完成！"
echo "=========================================="
echo ""
echo "建议重启系统以确保所有更改生效: sudo reboot"
echo ""

